/**
 * 
 */
package ru.opedge.notifical.notification.service.google;

import java.util.TimeZone;

import ru.opedge.notifical.notification.Notification;
import ru.opedge.notifical.util.StringLengthSplitter;
import ru.opedge.notifical.util.transliteration.Transliterator;

import com.google.gdata.data.DateTime;
import com.google.gdata.data.PlainTextConstruct;
import com.google.gdata.data.batch.BatchOperationType;
import com.google.gdata.data.batch.BatchUtils;
import com.google.gdata.data.calendar.CalendarEventEntry;
import com.google.gdata.data.calendar.CalendarEventFeed;
import com.google.gdata.data.extensions.Reminder;
import com.google.gdata.data.extensions.When;
import com.google.gdata.data.extensions.Reminder.Method;

/**
 * @author opedge
 * 
 */
public class GCalSmsService extends GCalService
{
	/**
	 * @param appName
	 * @param postUrl
	 */
	public GCalSmsService(final String appName)
	{
		super(appName);
	}

	/*
	 * Transliteration
	 */
	private Notification transliterateNotification(
			final Notification notification)
	{
		final Transliterator t = Transliterator.getInstance("Cyrillic-Latin");
		final String result = t.transliterate(notification.getText());
		notification.setText(result);
		return notification;
	}

	public static final int SMS_LENGTH_ML = 60;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * ru.opedge.notifical.notification.service.google.GCalService#getReminder()
	 */
	@Override
	public CalendarEventFeed getRequest(final Notification notification)
	{
		final CalendarEventFeed request = new CalendarEventFeed();
		final Notification notif = transliterateNotification(notification);
		final String text = notif.getText();
		for (final String msg : new StringLengthSplitter(text, SMS_LENGTH_ML))
		{
			final CalendarEventEntry entry = new CalendarEventEntry();
			entry.setTitle(new PlainTextConstruct(msg));

			final DateTime startTime = new DateTime(notif.getDate(), TimeZone
					.getTimeZone("GMT"));
			final DateTime endTime = new DateTime(notif.getDate(), TimeZone
					.getTimeZone("GMT"));

			final When eventTimes = new When();
			eventTimes.setStartTime(startTime);
			eventTimes.setEndTime(endTime);
			entry.addTime(eventTimes);

			final Reminder reminder = new Reminder();
			reminder.setMethod(Method.SMS);
			reminder.setMinutes(0);
			entry.getReminder().add(reminder);

			BatchUtils.setBatchId(entry, entry.getId());
			BatchUtils.setBatchOperationType(entry, BatchOperationType.INSERT);

			request.getEntries().add(entry);
		}
		return request;
	}
}
